package cn.shit;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TestStreamCreation {
    public static void main(String[] args) {
        // 使用Stream.of把数组变为stream
        // of是可变参数列表
        Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
        Integer[] ints = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
        integerStream = Stream.of(ints);
        show("Stream.of; ", integerStream);

        //可以使用Arrays.stream()截取数组作为stream
        integerStream = Arrays.stream(ints, 1, 2);
        show("Arrays.stream; ", integerStream);

        // 空流
        //Stream.empty()

        Stream<String> stringStream = Stream.generate(() -> "ECHO");
        show("Stream.generate1; ", stringStream);
        Stream<Double> doubleStream = Stream.generate(Math::random);// "::" method reference
        show("Stream.generate2; ", doubleStream);

        // 迭代无限流
        Stream<BigInteger> bigIntegerStream = Stream.iterate(BigInteger.ONE,
                n -> n.add(BigInteger.ONE));
        show("Stream.iterate; ", bigIntegerStream);

        // files.lines
        try (Stream<String> lineStream = Files.
                lines(Paths.get("D:\\IDEA\\Code021\\src\\cn\\shit\\shit.txt"))) {
            show("Files.lineStream", lineStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static <T> void show(String title, Stream<T> stream) {
        final int SIZE = 5;
        List<T> firstElements = stream
                .limit(SIZE + 1)
                .collect(Collectors.toList());
        System.out.print(title + ": ");
        for (int i = 0; i < firstElements.size(); i++) {
            if (i > 0) System.out.print(", ");
            if (i < SIZE) System.out.print(firstElements.get(i));
            else System.out.print("...");
        }
        System.out.println();
    }
}
